package it.unibz.easytravel.travel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import it.unibz.easytravel.R;
import it.unibz.easytravel.common.Person;
import it.unibz.easytravel.db.TravelDbAdapter;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AddTravel extends Activity {

	
	private static int travel_id;

	private static LinearLayout travelersList;
	private static List<Person> travellers;
	private static Activity activity;
	public static final String PREFS_NAME = "EasyTravelPrefsFile";
	public static final String TRAVEL_ID = "current_travel_id";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.travel_add);

		SharedPreferences settings = getSharedPreferences(EditTravel.PREFS_NAME, 0);
		travel_id = settings.getInt(EditTravel.TRAVEL_ID, -1);
	
		
		Button button_createTravel = (Button) findViewById(R.id.button_createTravel);
		button_createTravel.setOnClickListener(mCreateTravel);
		
		travellers = new ArrayList<Person>();
		
		travelersList = (LinearLayout) findViewById(R.id.addTravel_travelersList);
		
		Button travellersButton = (Button) findViewById(R.id.addTravel_addTravelersButton);
		travellersButton.setOnClickListener(new AddTravelersButtonListener(this));
		this.activity = this;
	}
	
	
	// stub method for id generation
	private int GenerateTravelId () {
		return 1;
	}
	
	
	private void StoreChosenTravelInPrefs(long travelId) {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(TRAVEL_ID, (int)travelId);
		editor.commit();
	}
	
	
	
	private OnClickListener mCreateTravel = new OnClickListener() {
		public void onClick(View v) {
			EditText titleBox = (EditText) findViewById(R.id.travel_edit_title);
			String title =  titleBox.getText().toString();
			
			EditText descriptionBox = (EditText) findViewById(R.id.travel_edit_description);
			String description =  descriptionBox.getText().toString();
			
			Person creator = new Person("me", "this");
			Travel travel = new Travel(GenerateTravelId(), title, description, creator,travellers);
						
			//call the DB add
			TravelDbAdapter mTravelAdapter = new TravelDbAdapter(activity);
			mTravelAdapter.open();
			long travelId = mTravelAdapter.insertTravel(travel, activity);
			mTravelAdapter.close();

			if (travelId > -1) {
				activity.finish();
				StoreChosenTravelInPrefs(travelId);
				
			}
			else {
				throw new RuntimeException("Creation of Travel failed!!");
			}

		}
	};
	
	private class AddTravelersButtonListener implements OnClickListener {
		
		private Activity context;
		
		public AddTravelersButtonListener(Activity ctx) {
			this.context = ctx;
		}
		
		public void onClick(View v) {
			Intent intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI);
			startActivityForResult(intent,0);
			
		}
	};
	

	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
        	// and new traveller
        	if (resultCode == RESULT_OK) {
            	Cursor cur = managedQuery(data.getData(), null, null, null, null);
            	if (cur.moveToFirst()) {
                    int nameColumn = cur.getColumnIndexOrThrow(People.NAME); 
                    int numberColumn = cur.getColumnIndexOrThrow(People.NUMBER);
                    
                    // Get the field values
                    String personName = cur.getString(nameColumn);
                    String personNumber = cur.getString(numberColumn);
                	
                    if(!isInTravellersList(personNumber))
                    	travellers.add(new Person(personName, personNumber));
                }
            	
            	doIt();
        		
            }
        }
    }
	
	public static void doIt(){
		
		travelersList.removeAllViews();
    	int size = travellers.size();
    	for (int i = 0; i < size; i++) {
   		
    		LinearLayout l = new LinearLayout(activity);
    		
    		TextView text = new TextView(activity); 
        	text.setText(travellers.get(i).getName());
        	
        	Button button = new Button(activity);
        	button.setOnClickListener(new mClickedRemoveTravelerListener(travellers.get(i).getPhoneNumber(), activity));
        	button.setBackgroundResource(R.drawable.delete);
        	
        	l.addView( text);
        	l.addView( button);
        	
        	travelersList.addView(l);	
        	
		}
    	
	}
	
	public static class mClickedRemoveTravelerListener implements OnClickListener {

		private String phoneNr;
		private Activity activity;

		public mClickedRemoveTravelerListener(String phoneNr, Activity activity) {
			this.phoneNr = phoneNr;
			this.activity = activity;
		}

		public void onClick(View v) {
			int size = travellers.size();
        	for (int i = 0; i < size; i++) {
        		if(travellers.get(i).getPhoneNumber().equals(phoneNr)){
        			travellers.remove(i);
        			break;
        		}
        	}
        	doIt();
		}
	}
	
	/**
	 * Checks if person is already added in the travellers list
	 * @param telephone number
	 * @return true - if number is in the list, folse - otherwise
	 */
	protected boolean isInTravellersList(String number){
		int size = travellers.size();
    	for (int i = 0; i < size; i++)
    		if(travellers.get(i).getPhoneNumber().equals(number))
    			return true;
		return false;
	}
	
}
